package com.tt.mymu.config;

import com.tt.mymu.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在请求处理之前进行调用（Controller方法调用之前）
        User user = (User)request.getSession().getAttribute("user");
        if (user == null) {
            // 用户未登录，跳转到登录页面
            response.setStatus(4011);
            return false;
        }

        //System.out.println("preHandle");
        return true; // 如果返回false，则停止流程，api不会被调用
    }
/* const status = error.response.status;
        console.log(status); // 输出状态码，例如 401
        if (4011 === status) {
        console.log('err，没有权限')
    }*/
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
        //System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在整个请求结束之后调用，也就是在DispatcherServlet渲染了视图执行
        //System.out.println("afterCompletion");
    }
}
